<template>
	<jk-dialog
		:dialog-state="showDialog"
		title="批量开台"
		width="1000px"
		:confirm-btn-loading="confirmBtnLoading"
		:show-content-loading="showLoading"
		@on-cancel="onVisibleChange(false)"
		@on-confirm="onConfirmBtn"
		@on-visible-change="onVisibleChange"
	>
		<el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="140px" :show-message="false">
			<div ref="box1">
				<el-tag type="primary" effect="plain" class="margin-bottom-4">
					<span class="el-icon-tickets item-gap"></span>
					<span>基本信息</span>
				</el-tag>
				<jk-card>
					<el-row>
						<el-col :span="12">
							<el-form-item class="margin-bottom-0" label="开台时间" prop="startTime">
								<el-date-picker v-model="ruleForm.startTime" clearable type="datetime" style="width: 100%;" value-format="yyyy-MM-dd HH:mm:ss" placeholder="开台时间" @change="onTimeChange" />
							</el-form-item>
						</el-col>
						<el-col :span="12">
							<el-form-item class="margin-bottom-0" label="开台班次">
								<jk-input v-model="ruleForm.startScheduleShiftName" readonly placeholder=""></jk-input>
							</el-form-item>
						</el-col>
					</el-row>
				</jk-card>
			</div>
			<div ref="box2" class="margin-bottom-4 margin-top-10">
				<el-tag type="primary" effect="plain">
					<span class="el-icon-tickets item-gap"></span>
					<span>机台明细</span>
				</el-tag>
			</div>
			<jk-table
				:data="ruleForm.machineList"
				border
				highlight-hover-row
				highlight-current-row
				:height="dialogTableHeight - 30"
			>
				<vxe-column title="操作" align="center" field="operation" fixed="left" :width="64">
					<template slot-scope="scope">
						<el-button size="mini" icon="el-icon-remove" type="text" plain @click="ruleForm.machineList.splice(scope.rowIndex, 1)"></el-button>
					</template>
				</vxe-column>
				<vxe-column title="设备" align="center" field="machineName" :width="88">
					<template slot-scope="scope">
						<machineItemInfoPopover :machine-item="scope.row"></machineItemInfoPopover>
					</template>
				</vxe-column>
				<vxe-column title="品种" align="left" field="productName" :min-width="160" />
				<vxe-column title="批号" align="left" field="batchCode" :min-width="140" />
				<vxe-column title="开台锭数" align="right" field="openSpinCount" :width="90">
					<template slot-scope="scope">
						<jk-number-input v-model="scope.row.openSpinCount" size="mini"></jk-number-input>
					</template>
				</vxe-column>
				<!--<vxe-column title="系数" align="right" field="outputRatio" :width="80">
					<template slot-scope="scope">
						<jk-number-input v-model="scope.row.outputRatio" size="mini"></jk-number-input>
					</template>
				</vxe-column>-->
				<vxe-column title="产量表数(M)" align="right" field="startOutput" :width="120">
					<template slot-scope="scope">
						<jk-number-input v-model="scope.row.startOutput" size="mini"></jk-number-input>
					</template>
				</vxe-column>
				<vxe-column title="产量表数(kg)" align="right" field="startOutputKg" :width="120">
					<template slot-scope="scope">
						<jk-number-input v-model="scope.row.startOutputKg" size="mini"></jk-number-input>
					</template>
				</vxe-column>
				<!--<vxe-column title="产量采集表数" align="right" field="startSystemOutput" :width="100"></vxe-column>-->
				<vxe-column title="能耗表数" align="right" field="startElectricEnergy" :min-width="120">
					<template slot-scope="scope">
						<jk-number-input v-model="scope.row.startElectricEnergy" size="mini"></jk-number-input>
					</template>
				</vxe-column>
				<!--<vxe-column title="能耗采集表数" align="right" field="startSystemElectricEnergy" :min-width="100"></vxe-column>-->
			</jk-table>
		</el-form>

	</jk-dialog>
</template>

<script>
    import { clearRedundancyKey, formatTime, tipsBar } from '../../../../utils/jk/jk-tool';
    import { workforcemanagementScheduleShiftByTime } from '../../../../api/schedule/empReplacePost';
    import {
        productionPrdNoticeMachineChangeGetMachineDataList,
        productionPrdNoticeMachineOpeningBatchOpening,
        productionPrdNoticeMachineOpeningCheckOpening
    } from '../../../../api/production/xsOpen';
    import calHeight from '/src/mixins/cal-dialog-height';
    import machineItemInfoPopover from './machine-info-popover';
    export default {
        mixins: [calHeight],
        components: {
            machineItemInfoPopover
        },
        props: {
            dialogState: {
                type: Boolean,
                default: false
            },
            machineList: {
                type: Array,
                default() {
                    return [];
                }

            }
        },
        data() {
            return {
                showLoading: false,
                showDialog: false,
                confirmBtnLoading: false,
                ruleForm: {
                    'outputRatio': 1,
                    'endSpinNumber': null,
                    'lastEndElectricEnergy': null,
                    'lastEndOutput': null,
                    'openSpinCount': null,
                    'prdNoticeMachineChangeId': null,
                    'startElectricEnergy': null,
                    'startOutput': null,
                    'startScheduleShiftId': null,
                    'startScheduleShiftName': '',
                    'startSystemElectricEnergy': null,
                    'startSystemOutput': null,
                    'startTime': '',
                    'startSystemTime': '',
                    'spinCount': 0, // 机台的设定锭数
                    'usedSpinCount': 0, // 已经开台的锭数
                    'machineList': []
                },
                rules: {
                    startScheduleShiftName: [{ required: true, trigger: 'change' }],
                    startTime: [{ required: true, trigger: 'change' }]
                }
            };
        },
        methods: {
            onConfirmBtn() {
                this.$refs['ruleForm'].validate(valid => {
                    if (valid) {
                        const params = this.ruleForm.machineList.map(x => {
                            return {
                                // 'startScheduleShiftId': this.ruleForm.startScheduleShiftId,
                                'startSystemTime': this.ruleForm.startSystemTime,
                                'startTime': this.ruleForm.startTime,
                                'outputRatio': x.outputRatio,
                                'lastEndElectricEnergy': x.lastEndElectricEnergy,
                                'lastEndOutput': x.lastEndOutput,
                                'openSpinCount': x.openSpinCount,
                                'prdNoticeMachineChangeId': x.prdNoticeMachineChangeId,
                                'startElectricEnergy': x.startElectricEnergy,
                                'startOutput': x.startOutput,
                                'startSystemElectricEnergy': x.startSystemElectricEnergy,
                                'startSystemOutput': x.startSystemOutput,

                                'startOutputKg': x.startOutputKg,
                                'startSystemOutputKg': x.startSystemOutputKg
                            };
                        });
                        // 校验与采集的品种是否一致
                        productionPrdNoticeMachineOpeningCheckOpening(params).then(res => {
                            if (res.data.status === 200) {
                                const resData = res.data.res || [];
                                if (resData && resData.length) {
                                    const warningInfo = resData[0];
                                    this.$msgbox({
                                        title: '提示',
                                        message: `品种不一致，设备品种:"${warningInfo.machineProductName}"，计划品种:"${warningInfo.planProductName}"，确认继续"开台"吗？`,
                                        iconClass: 'el-icon-question',
                                        showCancelButton: true,
                                        confirmButtonText: '确定',
                                        cancelButtonText: '取消',
                                        beforeClose: (action, instance, done) => {
                                            if (action === 'confirm') {
                                                done();
                                                this.saveRequest(params);
                                            } else {
                                                done();
                                            }
                                        }
                                    });
                                } else {
                                    this.saveRequest(params);
                                }
                            }
                        });
                    } else {
                        this.$tipsBar(this, 'validator');
                    }
                });
            },
            saveRequest(params) {
                this.confirmBtnLoading = true;
                productionPrdNoticeMachineOpeningBatchOpening(params).then(res => {
                    this.confirmBtnLoading = false;
                    if (res.data.status === 200) {
                        this.$emit('on-confirm');
                    }
                });
            },
            onVisibleChange(e) {
                this.$emit('on-visible-change', e);
            },
            onTimeChange() {
                this.$set(this.ruleForm, 'startScheduleShiftId', null);
                this.$set(this.ruleForm, 'startScheduleShiftName', '');
                this.getScheduleShiftForTimeRequest();
                this.getGatherMachineDataRequest();
            },
            getScheduleShiftForTimeRequest() {
                if (this.ruleForm.workshopId && this.ruleForm.startTime) {
                    /* return workforcemanagementScheduleShiftByTime({
                        startTime: this.ruleForm.startTime,
                        workshopId: this.ruleForm.workshopId
                    }).then(res => {
                        if (res.data.status === 200) {
                            let resData = res.data.res;
                            if (!resData) {
                                tipsBar(this, 'custom', 'warning', '当前时间未排班，请排班后再操作！');
                                resData = { shiftId: null, shiftName: '' };
                            }
                            this.$set(this.ruleForm, 'startScheduleShiftId', resData.shiftId);
                            this.$set(this.ruleForm, 'startScheduleShiftName', resData.shiftName);
                        }
                    });*/
                }
            },
            // 获取指定机台采集的仪表数据
            getGatherMachineDataRequest() {
                if (this.ruleForm.startTime && this.ruleForm.machineList && this.ruleForm.machineList.length) {
                    return productionPrdNoticeMachineChangeGetMachineDataList({
                        machineIds: this.ruleForm.machineList.map(x => x.machineId),
                        selectDateTime: this.ruleForm.startTime
                    }).then(res => {
                        if (res.data.status === 200) {
                            const resData = res.data.res || [];
                            this.ruleForm.machineList.forEach(x => {
                                resData.forEach(k => {
                                    if (x.machineId === k.machineId) {
                                        // 开台能耗表数，默认等于采集到的实时能耗
                                        this.$set(x, 'startElectricEnergy', k.currentElectricEnergy);
                                        this.$set(x, 'startSystemElectricEnergy', k.currentElectricEnergy);
                                        // 开台产量表数，默认等于采集到的实时产量
                                        this.$set(x, 'startOutput', k.currentOutput);
                                        this.$set(x, 'startSystemOutput', k.currentOutput);
                                        // 上次的产量和能耗
                                        this.$set(x, 'lastEndOutput', k.lastEndOutput);
                                        this.$set(x, 'lastEndElectricEnergy', k.lastEndElectricEnergy);

                                        this.$set(x, 'openSpinCount', k.spinCount - k.usedSpinCount);
                                        this.$set(x, 'usedSpinCount', k.usedSpinCount);
                                        this.$set(x, 'spinCount', k.spinCount);

                                        this.$set(x, 'startOutputKg', k.currentOutputKg);
                                        this.$set(x, 'startSystemOutputKg', k.currentOutputKg);
                                    }
                                });
                            });
                        }
                    });
                }
            },
            async getDependentData() {
                this.showLoading = true;
                await this.getScheduleShiftForTimeRequest();
                await this.getGatherMachineDataRequest();
                this.$nextTick(() => {
                    this.$refs.ruleForm.clearValidate();
                });
                this.showLoading = false;
            }
        },
        watch: {
            dialogState(newVal) {
                const cpData = JSON.parse(JSON.stringify(this.machineList)).map(x => {
                    x.prdNoticeMachineChangeId = x.id;
                    x.spinCount = 0;
                    x.usedSpinCount = 0;
                    delete x.id;
                    return clearRedundancyKey(x);
                });
                let workshopIds = cpData.map(x => x.workshopId);
                workshopIds = Array.from(new Set(workshopIds));
                if (workshopIds.length > 1) {
                    tipsBar(this, 'custom', 'warning', '只能操作同一区域内机台!');
                } else {
                    const workshopItem = cpData && cpData.length ? cpData[0] : {};
                    this.$set(this.ruleForm, 'workshopId', workshopItem.workshopId);
                    this.$set(this.ruleForm, 'workshopCode', workshopItem.workshopCode);
                    this.$set(this.ruleForm, 'workshopName', workshopItem.workshopName);
                    this.$set(this.ruleForm, 'machineList', cpData);
                    this.$set(this.ruleForm, 'startSystemTime', formatTime(Date.now()));
                    this.$set(this.ruleForm, 'startTime', formatTime(Date.now()));
                    if (newVal) {
                        this.getDependentData();
                    }
                }
                this.showDialog = newVal;
            }
        }
    };
</script>
